package com.yyplatform.admin.platform.config.service.impl;

import java.util.List;

import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import com.yyplatform.admin.platform.config.model.dto.SysDictItemDTO;
import com.yyplatform.admin.platform.config.model.dto.SysDictItemFormDTO;
import com.yyplatform.admin.platform.config.model.dto.SysDictItemQueryDTO;
import com.yyplatform.admin.platform.config.model.entity.SysDictItemEntity;
import com.yyplatform.admin.platform.config.repository.SysDictItemRepository;
import com.yyplatform.admin.platform.config.service.SysDictItemService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author sleepforests@163.com
 * <p>
 * Created on 2024/9/21 21:23
 */
@Service
@Slf4j
@AllArgsConstructor
public class SysDictItemServiceImpl implements SysDictItemService {

    private SysDictItemRepository sysDictItemRepository;
    private ModelMapper modelMapper;


    @Override
    public void delete(Long id) {
        sysDictItemRepository.deleteById(id);
    }

    @Override
    public void update(SysDictItemFormDTO formDTO) {
        SysDictItemEntity entity = modelMapper.map(formDTO, SysDictItemEntity.class);
        sysDictItemRepository.save(entity);
    }

    @Override
    public void save(SysDictItemFormDTO sysDictFormDTO) {
        SysDictItemEntity entity = modelMapper.map(sysDictFormDTO, SysDictItemEntity.class);
        entity.setIsDefault(true);

        sysDictItemRepository.save(entity);
    }

    @Override
    public SysDictItemDTO get(Long id) {
        SysDictItemEntity entity = sysDictItemRepository.getReferenceById(id);
        return modelMapper.map(entity, SysDictItemDTO.class);
    }

    @Override
    public Page<SysDictItemDTO> query(SysDictItemQueryDTO pageQueryDTO) {
        Page<SysDictItemEntity> entityPage =
                sysDictItemRepository.findByDictId(
                        pageQueryDTO.getDictId(),
                        pageQueryDTO.getPageRequestOrderByIdDesc());

        List<SysDictItemDTO> list = entityPage.stream()
                .map(e -> modelMapper.map(e, SysDictItemDTO.class))
                .toList();

        return new PageImpl<>(list, entityPage.getPageable(), entityPage.getTotalElements());
    }
}
